import 'dart:io';

// import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sp_util/sp_util.dart';
// import 'package:tencent_kit/tencent_kit.dart';
import 'package:friends_flutter/config/service/device_info.dart';
import 'package:friends_flutter/config/service/record_mp3_service.dart';
import 'package:friends_flutter/config/service/upload_service.dart';
import '../utils/common_sp_util.dart';
import '../utils/log_utils.dart';
import 'constants.dart';

///环境配置
Environment environment = Environment.uat;

//打渠道包
//flutter build apk --dart-define=APP_CHANNEL=lovein
// const String channelPackage = String.fromEnvironment('APP_CHANNEL');
const String channelPackage = ChannelPackage.normal;


enum Environment {
  development, //开发环境
  production, //生产环境
  uat; //验收环境

  static Environment fromString(String value, {Environment defaultValue = Environment.uat}) {
    try {
      return Environment.values.firstWhere((element) =>
      element.toString().split('.')[1] == value.toLowerCase());
    } catch (e) {
      return defaultValue;
    }
  }
}

// extension EnvironmentExtension on Environment {
//   static Environment fromString(String value, {Environment defaultValue = Environment.uat}) {
//     try {
//       return Environment.values.firstWhere((element) =>
//       element.toString().split('.')[1] == value.toLowerCase());
//     } catch (e) {
//       return defaultValue;
//     }
//   }
// }

//渠道包 (头条 百度 OPPO vivo 华为)
class ChannelPackage {
  static const String normal = 'normal'; //普通渠道
  static const String oPPO = 'oPPO'; //OPPO
  static const String vivo = 'vivo'; //vivo
  static const String huaWei = 'huaWei'; //华为
  static const String xiaoMi = 'xiaoMi'; //小米
  static const String tengXun = 'tengXun'; //腾讯应用宝
  static const String appleStore = 'appleStore'; //苹果商店
  static const String appleTestFlight = 'appleTestFlight'; //苹果测试
}

class AppConfig {
  static Future<void> init() async {
    /// 初始化本地数据存储
    await SpUtil.getInstance();
    //环信IM
    //await Get.putAsync(() => EmImService().initSDK());
    // await Get.put(TimImService()).initSDK();
    //同意协议之后
    await Get.put(DeviceInfo()).initPlatformState();
    initthirdparty();
    Get.put(UploadService());
    Get.put(RecordMp3Service());
    environment = CommonSpUtil.getServerEnvironment();

    EnvironmentConst.init();

    //检测是否安装微信
    // LoginManger.isWeChatInstalled1();

  }

  //初始化Hive数据库
  static initHive() async {
    final directory = await getApplicationDocumentsDirectory();
    Hive.init(directory.path);
    Hive.registerAdapter(UploadTaskModelAdapter());
    try {
      await Hive.openBox(Constants.hiveDatabase);
    } catch (e) {
      print('initHive = $e');
    }
    print('initHive 333333333');
  }

  /// 初始化第三方库
  static initthirdparty() async {
    //日志输出
    getDataFile().then((value) {
      logger = Logger(
        output: (value is File) ? FileOutput(file: value) : null,
        filter: ProductionFilter(),
        printer: SimplePrinter(printTime: true, colors: false),
      );
    });
    initHive();
    initTencent();
    initWeixin();
  }

  //qq
  static initTencent() async {
    // await Tencent.instance.setIsPermissionGranted(granted: true);
    // Tencent.instance.registerApp(appId: '102031683').whenComplete(() {
    //   LogUtilTool.println('QQ登录SDK注册完成 ---- ');
    // });
  }

  //微信
  static initWeixin() {
    // registerWxApi(
    //     appId: Constants.wxAppID,
    //     doOnAndroid: true,
    //     doOnIOS: true,
    //     universalLink: "https://www.xdan.club/app/");  //https://www.applovein.com
  }
}

Future<File> getDataFile() async {
  //上传日志
  Directory? data;
  if (Platform.isIOS) {
    data = await getTemporaryDirectory();
  } else {
    data = await getExternalStorageDirectory();
  }
  String tempPath = data?.path ?? '';
  File txt = File('$tempPath/xdanapplog/xdan.log');
  await txt.create(recursive: true);
  return txt;
}

//日志输出
Logger? logger;

///环境常量配置
///
class EnvironmentConst {
  static late String apiBaseUrl; //http base URL
  static late String apiImageBaseUrl; //图片base URL
  // static late String webSocketUrl; //webSocket服务
  // static late String agoraAppId; //声网ID

  ///环境常量配置初始化
  static void init() {
    if (environment == Environment.development) {
      _dev();
    } else if (environment == Environment.uat) {
      _uat();
    } else {
      _prod();
    }
  }

  ///测试环境(内网)
  static _dev() async {
    apiBaseUrl = 'http://42.194.132.195:9080/edu';
    apiImageBaseUrl = 'https://ainote-s3-us.s3.us-west-1.amazonaws.com/';
  }

  ///生产环境
  static _prod() async {

  }

  ///uat环境
  static _uat() async {
    apiBaseUrl = 'http://42.194.132.195:9080/edu';
    apiImageBaseUrl = 'https://ainote-s3-us.s3.us-west-1.amazonaws.com/';
  }

  //用于日志名称
  // static final String leyinlogName =
  //     '${DateTime.now().millisecondsSinceEpoch}leyin.log';
}